package com.zbkj.crmeb.store.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.annotation.UnitConvertUtil;
import com.crmeb.core.config.MybatisPlusConfig;
import com.crmeb.core.exception.CrmebException;
import com.crmeb.core.utils.TableNameUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.utils.CrmebUtil;
import com.utils.DateUtil;
import com.utils.PriceUtil;
import com.utils.ProductConvertUtil;
import com.utils.vo.dateLimitUtilVo;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.enums.AreaTypeEnum;
import com.zbkj.crmeb.enums.MarkupRateTypeEnum;
import com.zbkj.crmeb.enums.ProductTypeEnum;
import com.zbkj.crmeb.front.vo.RatioVo;
import com.zbkj.crmeb.member.enums.EquityTypeEnum;
import com.zbkj.crmeb.member.model.MerchantMemberBenefits;
import com.zbkj.crmeb.member.model.StoreProductDiscount;
import com.zbkj.crmeb.member.service.IMerchantMemberBenefitsService;
import com.zbkj.crmeb.member.service.IStoreProductDiscountService;
import com.zbkj.crmeb.store.dao.StoreProductDao;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.request.BatchEnabledRequest;
import com.zbkj.crmeb.store.request.MarkupRateRequest;
import com.zbkj.crmeb.store.request.StoreProductRuleSearchRequest;
import com.zbkj.crmeb.store.request.StoreProductSearchRequest;
import com.zbkj.crmeb.store.response.StoreProductAttrValueResponse;
import com.zbkj.crmeb.store.response.StoreProductNormResponse;
import com.zbkj.crmeb.store.response.StoreProductResponse;
import com.zbkj.crmeb.store.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class StoreProductSelectionServiceImpl implements StoreProductSelectionService {

    @Autowired
    private PriceUtil priceUtil;
    @Resource
    private StoreProductDao storeProductDao;
    @Autowired
    private ProductConvertUtil productConvertUtil;
    @Autowired
    private StoreZoneService storeZoneService;
    @Autowired
    private StoreZoneProductService storeZoneProductService;
    @Autowired
    private IMerchantMemberBenefitsService merchantMemberBenefitsService;
    @Autowired
    private IStoreProductDiscountService storeProductDiscountService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private ICategoryMatchService categoryMatchService;
    @Autowired
    private MarkupRateService markupRateService;
    @Autowired
    private StoreSaleAnalysisService storeSaleAnalysisService;
    @Autowired
    private StoreBannerSetUpService storeBannerSetUpService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private StoreModuleSetUpService storeModuleSetUpService;
    @Autowired
    private StoreProductMerService storeProductMerService;
    @Autowired
    private StoreProductRuleService storeProductRuleService;

    /**
     * 列表
     * @param request 请求参数
     * @param pageParamRequest 分页类参数
     * @author Mr.Zhang edit by wangzh
     * @since 2022-10-27
     * @return PageInfo<StoreProductResponse>
     */
    @Override
    public PageInfo<StoreProductResponse> getMerchnatList(StoreProductSearchRequest request, PageParamRequest pageParamRequest, Integer merId){
        log.info("--------------- 查询商品列表, 当前的商户merId: {}, 查询条件: {} ---------------", merId, JSON.toJSONString(request));
        //获取查询语句
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = getQueryWrapper(request, merId);
        //销量map
        Map<Integer, Integer> payProductNumMap = new HashMap<>();
        //昨日热销
        if (8 == request.getType()){
            String startTime = LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern(Constants.DATE_FORMAT_START));
            String endTime = LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern(Constants.DATE_FORMAT_END));
            PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
            List<StoreProductActive> storeProductActives = storeSaleAnalysisService.list(Wrappers.<StoreProductActive>query().select("product_id", "sum(pay_product_number) as pay_product_number")
                    .lambda().in(StoreProductActive::getMerId, merId)
                    .between(StoreProductActive::getUpdateTime, startTime, endTime)
                    .groupBy(StoreProductActive::getProductId)
                    .having("pay_product_number > 0")
                    .orderByDesc(StoreProductActive::getPayProductNumber));
            //昨日商户下商品有售卖情况
            if (CollectionUtils.isNotEmpty(storeProductActives)){
                //商品与支付次数对应map
                payProductNumMap = storeProductActives.stream().collect(Collectors.toMap(StoreProductActive::getProductId, StoreProductActive::getPayProductNumber));
                //当前商户下有支付次数的商品id
                List<Integer> ids = storeProductActives.stream().map(StoreProductActive::getProductId).collect(Collectors.toList());
                lambdaQueryWrapper.in(StoreProduct::getId, ids);
            }
        }
        //近30天热销
        if (9 == request.getType()){
            String startTime = LocalDate.now().minusDays(30).format(DateTimeFormatter.ofPattern(Constants.DATE_FORMAT_START));
            String endTime = LocalDate.now().format(DateTimeFormatter.ofPattern(Constants.DATE_FORMAT_END));
            PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
            List<StoreProductActive> storeProductActives = storeSaleAnalysisService.list(Wrappers.<StoreProductActive>query().select("product_id", "sum(pay_product_number) as pay_product_number")
                    .lambda().in(StoreProductActive::getMerId, merId)
                    .between(StoreProductActive::getUpdateTime, startTime, endTime)
                    .groupBy(StoreProductActive::getProductId)
                    .having("pay_product_number > 0")
                    .orderByDesc(StoreProductActive::getPayProductNumber));
            //近30天商户下商品有售卖情况
            if (CollectionUtils.isNotEmpty(storeProductActives)){
                //商品与支付次数对应map
                payProductNumMap = storeProductActives.stream().collect(Collectors.toMap(StoreProductActive::getProductId, StoreProductActive::getPayProductNumber));
                //当前商户下有支付次数的商品id
                List<Integer> ids = storeProductActives.stream().map(StoreProductActive::getProductId).collect(Collectors.toList());
                lambdaQueryWrapper.in(StoreProduct::getId, ids);
            }
        }
        Page<StoreProduct> storeProductPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<StoreProduct> storeProducts = storeProductDao.selectList(lambdaQueryWrapper);
        if(CollectionUtils.isEmpty(storeProducts)) {
            if (8 == request.getType()){
                LambdaQueryWrapper<StoreProduct> queryWrapper = getQueryWrapper(request, merId);
                storeProductPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
                storeProducts = storeProductDao.selectList(queryWrapper);
            } else if (9 == request.getType()){
                LambdaQueryWrapper<StoreProduct> queryWrapper = getQueryWrapper(request, merId);
                queryWrapper.orderByDesc(StoreProduct::getPrice);
                storeProductPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
                storeProducts = storeProductDao.selectList(queryWrapper);
            } else {
            	return CommonPage.copyPageInfo(storeProductPage, new ArrayList<>());
            }
        }

        /******** 查询对应属性表数据(弃用循环查询, 优化搜索速度) author: daigb ********/
        List<Integer> ids = storeProducts.stream().map(StoreProduct::getId).collect(Collectors.toList());
        // 匹配详情属性(只在活动列表里面查询)
        if(BooleanUtil.isTrue(request.getMerUse())) {
            productConvertUtil.convertProduct(storeProducts);
        } else {
            productConvertUtil.convertProductImage(storeProducts);
        }
        // 查询加价率, 计算价格
        priceUtil.calcProductPrice(storeProducts, merId, AreaTypeEnum.CN.getType());

        //查询商户是否开启会员指定商品折扣
        MerchantMemberBenefits merchantMemberBenefits = merchantMemberBenefitsService.getOne(Wrappers.lambdaQuery(MerchantMemberBenefits.class)
                .eq(MerchantMemberBenefits::getMerId,merId)
                .eq(MerchantMemberBenefits::getEquityEnableFlag,true)
                .eq(MerchantMemberBenefits::getEquityType, EquityTypeEnum.DISCOUNT.getCode())
                .eq(MerchantMemberBenefits::getDiscountConditions,2));
        List<Integer> discountList = new ArrayList<>();
        if (Objects.nonNull(merchantMemberBenefits)){
            List<StoreProductDiscount> productDiscountList = storeProductDiscountService.list(Wrappers.lambdaQuery(StoreProductDiscount.class)
                    .eq(StoreProductDiscount::getMerId,merId).in(StoreProductDiscount::getProductId,ids));
            discountList = productDiscountList.stream().map(StoreProductDiscount::getProductId).collect(Collectors.toList());
        }
        // 循环赋值
        List<StoreProductResponse> storeProductResponses = new ArrayList<>();
        for(StoreProduct product : storeProducts) {
            // 对象复制
            StoreProductResponse storeProductResponse = new StoreProductResponse();
            BeanUtils.copyProperties(product, storeProductResponse);

            // 通过原价算折扣率 ----处理
            if (storeProductResponse.getOtPrice() != null && storeProductResponse.getOtPrice().intValue() > 0) {
                BigDecimal bigDecimal = priceUtil.calcDiscount(storeProductResponse.getCost(), storeProductResponse.getOtPrice(), storeProductResponse.getExchangeRate());
                if (null != bigDecimal) {
                    storeProductResponse.setDiscount(bigDecimal.toString() + "折");
                }
            }
            //设置商品是否会员折扣
            storeProductResponse.setMemberDiscountFlag(discountList.contains(storeProductResponse.getId()));
            storeProductResponses.add(storeProductResponse);
        }
        List<Supplier> visibleSupplier = supplierService.getVisibleSupplier(merId);
        storeProductResponses.stream().forEach(storeProductResponse -> {
            //判断供应商名称是否商户可见
            if (visibleSupplier.stream().noneMatch(supplier -> Objects.equals(supplier.getId().toString(),storeProductResponse.getSuppliersId()+""))){
                storeProductResponse.setSuppliersName(null);
            }
        });
        /******** end *******/
        //给销量赋值
        Map<Integer, Integer> finalPayProductNumMap = payProductNumMap;
        storeProductResponses.forEach(e -> {
            e.setSales(null == finalPayProductNumMap.get(e.getId()) ? 0 : finalPayProductNumMap.get(e.getId()));
        });

        return CommonPage.copyPageInfo(storeProductPage, storeProductResponses);
    }

    /**
     * @Description: 获取banner详情
     * @param bannerId
     * @param pageParamRequest
     * @Return: java.util.Map<java.lang.String,java.lang.Object>
     * @Author: wangzh
     * @Date: 2022/10/28 15:41
     */
    @Override
    public Map<String, Object> getBannerDetails(Integer bannerId, PageParamRequest pageParamRequest, Integer merId) {
        if (null == bannerId){
            throw new CrmebException("bannerId不能为空");
        }

        StoreBannerSetUp storeBannerSetUp = storeBannerSetUpService.getById(bannerId);
        if (Objects.isNull(storeBannerSetUp)){
            throw new CrmebException("banner不存在");
        }
        Map<String, Object> response = new HashMap<>();
        response.put("backgroundImage", storeBannerSetUp.getBgImage());
        JSONObject jsonObject = JSONObject.parseObject(storeBannerSetUp.getJumpObject());
        switch (storeBannerSetUp.getType()){
            case PRODUCT:
                String productIds = jsonObject.getString("productId");
                List<Integer> productIdsList = Arrays.stream(productIds.split(",")).map(Integer::valueOf).collect(Collectors.toList());
                PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
                List<StoreProduct> listInIds = storeProductService.getListInIds(productIdsList);
                CommonPage<StoreProduct> page = CommonPage.restPage(listInIds);
                response.put("productInfo", page);
                break;
            case MODULE:
                Integer moduleId = jsonObject.getInteger("moduleId");
                StoreModuleSetUp storeModuleSetUp = storeModuleSetUpService.getById(moduleId);
                if (Objects.nonNull(storeModuleSetUp)){
                    String moduleProductIds = storeModuleSetUp.getProductIds();
                    List<Integer> moduleProductIdList = Arrays.stream(moduleProductIds.substring(1, moduleProductIds.length() - 1).split(",")).map(String::trim).map(Integer::valueOf).collect(Collectors.toList());
                    PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
                    List<StoreProduct> listInIds1 = storeProductService.getListInIds(moduleProductIdList);
                    CommonPage<StoreProduct> page1 = CommonPage.restPage(listInIds1);
                    response.put("productInfo", page1);
                }
                break;
            case BRAND:
                String brandId = jsonObject.getString("brandId");
                StoreProductSearchRequest searchRequest = new StoreProductSearchRequest();
                searchRequest.setType(1).setBrandId(brandId).setIsNotEurope(Arrays.asList(ProductTypeEnum.INSIDE.getCode()));
                LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = getQueryWrapper(searchRequest, merId);
                PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
                List<StoreProduct> list = storeProductService.list(lambdaQueryWrapper);
                productConvertUtil.convertProduct(list);
                CommonPage<StoreProduct> page2 = CommonPage.restPage(list);
                response.put("productInfo", page2);
                break;
        }
        return response;
    }

    /**
     * @Description: 模块详情
     * @param moduleId
     * @param pageParamRequest
     * @Return: java.util.Map<java.lang.String,java.lang.Object>
     * @Author: wangzh
     * @Date: 2022/10/28 14:17
     */
    @Override
    public Map<String, Object> getModuleDetails(Integer moduleId, PageParamRequest pageParamRequest) {
        if (null == moduleId){
            throw new CrmebException("模块id不能为空");
        }

        StoreModuleSetUp storeModuleSetUp = storeModuleSetUpService.getById(moduleId);
        if (Objects.isNull(storeModuleSetUp)){
            throw new CrmebException("模块不存在");
        }
        Map<String, Object> response = new HashMap<>();
        response.put("moduleImage", storeModuleSetUp.getImage());
        String productIds = storeModuleSetUp.getProductIds();
        System.out.println(productIds.substring(1, productIds.length() - 1));
        List<Integer> productIdsList = Arrays.stream(productIds.substring(1, productIds.length() - 1).split(",")).map(String::trim).map(Integer::valueOf).collect(Collectors.toList());
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<StoreProduct> listInIds = storeProductService.getListInIds(productIdsList);
        CommonPage<StoreProduct> page = CommonPage.restPage(listInIds);
        response.put("productInfo", page);
        return response;
    }

    /**
     * 功能描述: 获取商品详情
     * @Param: [productId, merId]
     * @Return: java.util.Map<java.lang.String,java.lang.Object>
     * @Author: wangzh
     * @Date: 2022/10/31 16:07
     */
    @Override
    public Map<String, Object> getProductInfo(Integer productId, Integer merId) {
        Map<String, Object> response = new HashMap<>();
        StoreProductSearchRequest request = new StoreProductSearchRequest();
        List<Integer> isNotEurope = Arrays.asList(ProductTypeEnum.INSIDE.getCode());
        request.setIsNotEurope(isNotEurope);
        //获取该商户下所有商品sql
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = getQueryWrapper(request, merId);
        //获取是否有该商品sql
        lambdaQueryWrapper.eq(StoreProduct::getId, productId).last("limit 1");
        StoreProduct one = storeProductDao.selectOne(lambdaQueryWrapper);
        //entity为空，说明该商户没有商品权限
        if (Objects.isNull(one)){
            response.put("power", false);
        } else {
            response.put("power", true);
        }
        //查询商品信息
        StoreProduct storeProduct = storeProductService.getOne(Wrappers.<StoreProduct>lambdaQuery()
                .eq(StoreProduct::getId, productId)
                .last("limit 1"));
        //标品id不为空查询绑定标品的所有商品
        out:if (null != storeProduct.getNormId()){
            //标品id不为空
            StoreProductNormResponse detail = storeProductService.getSupplierByNormId(storeProduct.getNormId());
            List<StoreProductResponse> products = detail.getProducts();
            //不包含当前商品的商品信息
            List<StoreProductResponse> storeProductResponses = products.stream().filter(i -> !productId.equals(i.getId())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(storeProductResponses)){
                break out;
            }
            List<Integer> supplierIds = storeProductResponses.stream().map(StoreProductResponse::getSuppliersId).collect(Collectors.toList());
            List<Supplier> suppliers = supplierService.list(Wrappers.<Supplier>lambdaQuery()
                    .in(Supplier::getId, supplierIds));
            Map<Integer, String> nameCodeMap = suppliers.stream().peek(i -> {
                if (null == i.getNameCode()) {
                    i.setNameCode("");
                }
            }).collect(Collectors.toMap(Supplier::getId, Supplier::getNameCode));
            Map<Integer, Integer> suppliersTypeMap = suppliers.stream().peek(i -> {
                if (null == i.getSupplierType()) {
                    i.setSupplierType(0);
                }
            }).collect(Collectors.toMap(Supplier::getId, Supplier::getSupplierType));
            List<Map<String, Object>> suppliersInfo = new ArrayList<>();
            for (StoreProductResponse productResponse : storeProductResponses){
                Map<String, Object> map = new HashMap<>();
                List<StoreProductAttrValueResponse> attrValue = productResponse.getAttrValue();
                //获取价格区间
                for (int i = 0; i < attrValue.size(); i++) {
                    StoreProductAttrValueResponse r = attrValue.get(i);
                    if (i == 0){
                        map.put("maxPrice", r.getPrice());
                        map.put("minPrice", r.getPrice());
                        continue;
                    }
                    //下一个sku的价格比最低价小
                    if (r.getPrice().compareTo((BigDecimal) map.get("minPrice")) < 0){
                        map.put("minPrice", r.getPrice());
                    }
                    //下一个sku价格比最高价大
                    if (r.getPrice().compareTo((BigDecimal) map.get("maxPrice")) > 0){
                        map.put("maxPrice", r.getPrice());
                    }
                }
                map.put("suppliersNameCode", nameCodeMap.get(productResponse.getSuppliersId()));
                map.put("suppliersType", suppliersTypeMap.get(productResponse.getSuppliersId()));
                map.put("productId", productResponse.getId());
                map.put("stock", productResponse.getStock());
                suppliersInfo.add(map);
            }
            //供应商信息
            response.put("suppliersInfo", suppliersInfo);
        }

        StoreProductResponse detail = storeProductService.getByProductId(productId);
        Integer suppliersId = detail.getSuppliersId();
        //设置供应商编号
        Supplier supplier = supplierService.getById(suppliersId);
        detail.setSuppliersNameCode(supplier.getNameCode());
        detail.setSuppliersType(supplier.getSupplierType());
        //查询月销量
        StoreProductActive sale = storeSaleAnalysisService.getOne(Wrappers.<StoreProductActive>query().select("sum(pay_product_number) as pay_product_number")
                .lambda().eq(StoreProductActive::getProductId, productId)
                .between(StoreProductActive::getUpdateTime, LocalDate.now().minusDays(30), LocalDateTime.now()).last("limit 1"));
        detail.setSales(0);
        if (Objects.nonNull(sale)){
            detail.setSales(sale.getPayProductNumber());
        }
        //查询多少商家上架
        List<ChannelMerchant> channelMerchants = channelMerchantService.list(Wrappers.<ChannelMerchant>lambdaQuery()
                .eq(ChannelMerchant::getChannelType, 1)
                .eq(ChannelMerchant::getIsDel, 0));
        List<Integer> merIds = new ArrayList<>();
        if (Objects.nonNull(channelMerchants)){
            merIds = channelMerchants.stream().map(ChannelMerchant::getId).collect(Collectors.toList());
        }
        int shelves = 0;
        for (Integer id: merIds){
            MybatisPlusConfig.tableNameMp.set(TableNameUtil.getProductMerName(id));
            int count = storeProductMerService.count(Wrappers.<StoreProductMer>lambdaQuery()
                    .eq(StoreProductMer::getProductId, productId));
            shelves += count;
        }

        //shelves家商户上架
        response.put("shelves", shelves);
        //商品信息
        response.put("productInfo", detail);
        if (!response.containsKey("suppliersInfo")){
            response.put("suppliersInfo", null);
        }
        //商品详情规则
        StoreProductRuleSearchRequest searchRequest = new StoreProductRuleSearchRequest();
        searchRequest.setCateId(detail.getCateId());
        //商家是否上架
        StoreProductMer storeProductMer = storeProductMerService.getOne(Wrappers.<StoreProductMer>lambdaQuery()
                .eq(StoreProductMer::getProductId, productId).last("limit 1"));
        detail.setMerIsShow(1);
        if (Objects.nonNull(storeProductMer)){
            if (storeProductMer.getIsNotShow().equals("1")){
                detail.setMerIsShow(0);
            }
        }
        response.put("rule", storeProductRuleService.getRuleByCate(searchRequest));
        return response;
    }

    /**
     * 功能描述: 上架商品
     * @Param: [token, productId]
     * @Return: java.lang.Boolean
     * @Author: wangzh
     * @Date: 2022/10/31 9:59
     */
    @Override
    public Boolean putOnShelves(String token, Integer productId) {
        List<Integer> productIds = Arrays.asList(productId);
        BatchEnabledRequest vo = new BatchEnabledRequest();
        vo.setProductIdList(productIds).setIsNotShow("0");
        return storeProductMerService.batchEnabled(token, vo);
    }

    /**
     * 功能描述: 为你推荐
     * @Param: [request, merId]
     * @Return: java.util.List<com.zbkj.crmeb.store.response.StoreProductResponse>
     * @Author: wangzh
     * @Date: 2022/10/31 17:05
     * @return
     */
    @Override
    public PageInfo<StoreProductResponse> recommendToYou(PageParamRequest request, Integer merId) {
        StoreProductSearchRequest searchRequest = new StoreProductSearchRequest();
        searchRequest.setIsNotEurope(Arrays.asList(ProductTypeEnum.INSIDE.getCode()));
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = getQueryWrapper(searchRequest, merId);
        lambdaQueryWrapper.last(",stock * 3 + sales * 7 desc");
        Page<Object> page = PageHelper.startPage(request.getPage(), request.getLimit());
        List<StoreProduct> list = storeProductService.list(lambdaQueryWrapper);
        productConvertUtil.convertProductImage(list);
        List<StoreProductResponse> responses = new ArrayList<>();
        for (StoreProduct storeProduct : list){
            StoreProductResponse response = new StoreProductResponse();
            BeanUtils.copyProperties(storeProduct, response);
            responses.add(response);
        }
        return CommonPage.copyPageInfo(page, responses);
    }

    private LambdaQueryWrapper<StoreProduct> getQueryWrapper(StoreProductSearchRequest request, Integer merId) {
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper =  new LambdaQueryWrapper<>();
        //获取渠道商户信息
        ChannelMerchant channelMerchant = channelMerchantService.getById(merId);
        if(channelMerchant == null){
            throw new CrmebException("该商户不存在");
        }
        Supplier supplier = supplierService.getSupplierBarcode(merId);
        List<String> brandIdsList= JSON.parseArray(channelMerchant.getBrandIds(), String.class);
        List<String> suppliersIdList = JSON.parseArray(channelMerchant.getSuppliersIds(), String.class);
        List<String> tempIdList = JSON.parseArray(channelMerchant.getTempId(), String.class);
        if(null!= brandIdsList && brandIdsList.size()>0){
            lambdaQueryWrapper.in(StoreProduct::getBrandId,brandIdsList);
        }
        if(null!= suppliersIdList && suppliersIdList.size()>0){
            if(null!=supplier){
                //商户如果是供应商的话 查询商户自建的商品 默认传入商户配置的供应商id
                suppliersIdList.add(supplier.getId().toString());
            }
        }
        if(null!= tempIdList && tempIdList.size()>0){
            lambdaQueryWrapper.in(StoreProduct::getTempId,tempIdList);
        }
        boolean inside = ProductTypeEnum.INSIDE.getCode().equals(request.getIsEurope());
        // 自建列表
        if(inside) {
            lambdaQueryWrapper.eq(StoreProduct::getIsEurope, ProductTypeEnum.INSIDE).eq(StoreProduct::getMerId, merId);
            //自建商品推送状态
            if(request.getSelfPushStatus() != null){
                lambdaQueryWrapper.eq(StoreProduct::getSelfPushStatus,request.getSelfPushStatus());
            }
        } else {
            //云仓 / 自建转云仓
            lambdaQueryWrapper.and(
                    e->e.in(CollectionUtils.isNotEmpty(suppliersIdList),StoreProduct::getSuppliersId,suppliersIdList).and(
                            a->a.ne(StoreProduct::getIsEurope, ProductTypeEnum.INSIDE)
                                    .or(b->b.eq(StoreProduct::getIsEurope, ProductTypeEnum.INSIDE)
                                            .ne(StoreProduct::getMerId,merId)
                                            .isNotNull(StoreProduct::getConvertIsEurope))
                    )
            );
        }
        //平台推荐
        if(BooleanUtil.isTrue(request.getPlatformRecommended())){
            List<StoreZone> storeZoneList = storeZoneService.list(Wrappers.lambdaQuery(StoreZone.class).eq(StoreZone::getMerId, merId).isNotNull(StoreZone::getPushZoneId).gt(StoreZone::getEndTime, new Date()));
            List<Integer> zoneIdList = storeZoneList.stream().map(StoreZone::getId).collect(Collectors.toList());
            List<StoreZoneProduct> storeZoneProductList = CollectionUtils.isNotEmpty(zoneIdList) ? storeZoneProductService.list(
                    Wrappers.lambdaQuery(StoreZoneProduct.class)
                            .in(StoreZoneProduct::getZoneId, zoneIdList)
            ) : new	ArrayList<>();

            List<Integer> recommendedProductIdList = storeZoneProductList.stream().map(StoreZoneProduct::getProductId).distinct().collect(Collectors.toList());
            lambdaQueryWrapper.in(StoreProduct::getId, CollectionUtils.isNotEmpty(recommendedProductIdList) ? recommendedProductIdList : Arrays.asList(-1));
        }

        //关键字搜索
        if (!StringUtils.isBlank(request.getKeywords())) {
            lambdaQueryWrapper.and(i -> i
                            .or().eq(NumberUtil.isInteger(request.getKeywords()), StoreProduct::getId, request.getKeywords())
                            .or().like(StoreProduct::getKeyword, request.getKeywords())
                            .or().like(StoreProduct::getStoreName, request.getKeywords())
//                    .or().like(StoreProduct::getStoreInfo, request.getKeywords())
                    .or().like(StoreProduct::getBarCode, request.getKeywords())
            );
        }
        if (BooleanUtil.isTrue(request.getIsBest())) {
            lambdaQueryWrapper.inSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE is_best = 1");
        }
        if(null != request.getPremiumType()){
            if(request.getPremiumType() == 0){
                lambdaQueryWrapper.notInSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE price_type != " + request.getPremiumType());
            }else {
                lambdaQueryWrapper.inSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE price_type = " + request.getPremiumType());
            }
        }
        //推荐图搜索
        if(BooleanUtil.isTrue(request.getRecommendFlag())) {
            lambdaQueryWrapper.inSql(request.getRecommendFlag(),StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE recommend_img IS NOT NULL AND LENGTH(trim(recommend_img)) > 0 ");
        }
        //会员折扣商品搜索
        if(BooleanUtil.isTrue(request.getMemberDiscountFlag())) {
            lambdaQueryWrapper.inSql(StoreProduct::getId, "SELECT product_id FROM eb_store_product_discount WHERE mer_id = " + merId);
        }
        if (request.getZoneId()!=null){
            List<StoreZoneProduct> storeZoneProduct = storeZoneProductService.list(Wrappers.<StoreZoneProduct>lambdaQuery().eq(StoreZoneProduct::getZoneId,request.getZoneId()));
            List<Integer> productIds = storeZoneProduct.stream().map(StoreZoneProduct::getProductId).distinct().collect(Collectors.toList());
            productIds.add(0);
            lambdaQueryWrapper.in(StoreProduct::getId, productIds);
        }

        //判断是否供应商筛选
        if (request.getSupplierId() != null) {
            lambdaQueryWrapper.eq(StoreProduct::getSuppliersId, request.getSupplierId());
        }
        if(CollectionUtils.isNotEmpty(request.getSupplierIds())){
            lambdaQueryWrapper.in(StoreProduct::getSuppliersId,request.getSupplierIds());
        }

        if (CollectionUtils.isNotEmpty(request.getStockAreas())) {
            lambdaQueryWrapper.in(StoreProduct::getTempId, request.getStockAreas());
        }
        if (StringUtils.isNotBlank(request.getBrandId())) {
            lambdaQueryWrapper.eq(StoreProduct::getBrandId, request.getBrandId());
        }
        if(CollectionUtils.isNotEmpty(request.getBrandIds())){
            lambdaQueryWrapper.in(StoreProduct::getBrandId,request.getBrandIds());
        }
        if (StringUtils.isNotBlank(request.getCateId())) {
            List<Integer> cateIds = categoryMatchService.getThreeChildVoListByPid(Integer.parseInt(request.getCateId())).stream().map(CategoryMatch::getId).collect(Collectors.toList());
            String cateIdStr = StringUtils.join(cateIds, ",");
            lambdaQueryWrapper.apply(CrmebUtil.getFindInSetSql("cate_id", cateIdStr));
        }
        if(CollectionUtils.isNotEmpty(request.getCateIds())){
            List<Integer> cateIds = new ArrayList<>();
            request.getCateIds().forEach(cateId->cateIds.addAll(categoryMatchService.getThreeChildVoListByPid(cateId).stream().map(CategoryMatch::getId).collect(Collectors.toList())));
            String cateIdStr = StringUtils.join(cateIds, ",");
            lambdaQueryWrapper.apply(CrmebUtil.getFindInSetSql("cate_id", cateIdStr));
        }

        // 最大小库存
        if(request.getMinStock() !=null && request.getMaxStock() == null){
            lambdaQueryWrapper.ge(StoreProduct::getStock,request.getMinStock());
        }else if(request.getMinStock() == null && request.getMaxStock() != null){
            lambdaQueryWrapper.le(StoreProduct::getStock,request.getMaxStock());
        }else if(request.getMinStock() !=null && request.getMaxStock() != null){
            lambdaQueryWrapper.between(StoreProduct::getStock,request.getMinStock(),request.getMaxStock());
        }
        if (null != request.getSeasonCode()) {
            if("-1".equals(request.getSeasonCode())) {
                lambdaQueryWrapper.isNull(StoreProduct::getSeasonCode);
            } else {
                lambdaQueryWrapper.likeRight(StoreProduct::getSeasonCode, request.getSeasonCode());
            }
        }

        if(!inside){
            //商户看到的云仓商品都是平台已上架的
            lambdaQueryWrapper.eq(StoreProduct::getIsShow, true);
        }
        //类型搜索
        switch (request.getType()) {
            case 1:
                //出售中（已上架）
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                if(inside){
                    lambdaQueryWrapper.eq(StoreProduct::getIsShow,true);
                }else {
                    //查询下架的商品ids
                    lambdaQueryWrapper.notInSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE is_not_show = 1");

                }
                // 库存为0的商品不显示在出售中列表
                lambdaQueryWrapper.gt(StoreProduct::getStock, 0);
                break;
            case 2:
                //仓库中（未上架）
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                if (inside) {
                    lambdaQueryWrapper.eq(StoreProduct::getIsShow, false);
                } else {
                    //查询下架的商品ids
                    lambdaQueryWrapper.inSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE is_not_show = 1");
                }
                break;
            case 3:
                //已售罄
                lambdaQueryWrapper.le(StoreProduct::getStock, 0);
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                break;
            case 4:
                //警戒库存
                //Integer stock = Integer.parseInt(systemConfigService.getValueByKey("store_stock"));
                lambdaQueryWrapper.gt(StoreProduct::getStock, 0);
                lambdaQueryWrapper.le(StoreProduct::getStock, 2);
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                break;
            case 5:
                //回收站
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, true);
                break;
            case 7 :
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                break;
            default:
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                break;
        }
        //自建商品二手/新品查询
        if (Objects.equals(ProductTypeEnum.INSIDE.getCode(),request.getIsEurope())){
            if (Objects.equals(1,request.getOrderType())){
                lambdaQueryWrapper.and(i -> i.or().isNull(StoreProduct::getDegree).or().eq(StoreProduct::getDegree,""));
            }
            if (Objects.equals(3,request.getOrderType())){
                lambdaQueryWrapper.isNotNull(StoreProduct::getDegree).ne(StoreProduct::getDegree,"");
            }
        }
        if(CollectionUtils.isNotEmpty(request.getPickingIds())){
            //查sku存在的商品
            lambdaQueryWrapper.inSql(StoreProduct::getId,"SELECT DISTINCT v.product_id FROM eb_store_product_picking p LEFT JOIN eb_store_product_attr_value v on p.sku_id = v.source_sku_id where p.picking_id in "+request.getPickingIds().toString().replace("[","(").replace("]",")"));
//            lambdaQueryWrapper.inSql(StoreProduct::getId,"SELECT DISTINCT product_id FROM eb_store_product_picking WHERE picking_id in "+request.getPickingIds().toString().replace("[","(").replace("]",")"));
        }
        if(CollectionUtils.isNotEmpty(request.getActivityIds())){
            lambdaQueryWrapper.inSql(StoreProduct::getId,"SELECT DISTINCT a.product_id FROM eb_store_product_activity a LEFT JOIN eb_store_product b on a.product_id = b.id where a.activity_id in "+request.getActivityIds().toString().replace("[","(").replace("]",")"));
        }
        if (request.isSellingBelowCost()) {
            lambdaQueryWrapper.apply(" price < cost ");
        }
        if (StringUtils.isNotBlank(request.getLabelName())) {
            lambdaQueryWrapper.inSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE label_id IN ( SELECT spl.id  FROM eb_store_product_label spl WHERE spl.label_name LIKE '%" + request.getLabelName() + "%' )");
        }
        //过滤分类
        List<Integer> integerList = categoryMatchService.selectCategoryMatchDisable(merId).stream().map(CategoryMatch::getId).collect(Collectors.toList());
        lambdaQueryWrapper.notIn(CollectionUtils.isNotEmpty(integerList), StoreProduct::getCateId, integerList);

        if(StringUtils.isNotBlank(request.getDateLimit())){
            dateLimitUtilVo dateLimit = DateUtil.getDateLimit(request.getDateLimit());
            lambdaQueryWrapper.between(StoreProduct::getCreateTime,dateLimit.getStartTime(),dateLimit.getEndTime());
        }

        MarkupRateRequest rateRequest = new MarkupRateRequest();
        rateRequest.setMerId(merId);
        rateRequest.setType(MarkupRateTypeEnum.PLAT_平台加价率.getType());
        BigDecimal platRatio = markupRateService.selectMerchantRatio(rateRequest);
        rateRequest.setType(MarkupRateTypeEnum.MERCHANT_商户加价率.getType());
        BigDecimal merRatio = markupRateService.selectMerchantRatio(rateRequest);
        //价格筛选
        if(request.getMinPrice() !=null || request.getMaxPrice() != null){
            if(request.getMinPrice() !=null && request.getMaxPrice() == null){
                lambdaQueryWrapper.ge(StoreProduct::getPrice, UnitConvertUtil.getInitialPrice(new BigDecimal(request.getMinPrice()),platRatio,merRatio));
            }else if(request.getMinPrice() == null && request.getMaxPrice() != null){
                lambdaQueryWrapper.le(StoreProduct::getPrice,UnitConvertUtil.getInitialPrice(new BigDecimal(request.getMaxPrice()),platRatio,merRatio));
            }else if(request.getMinPrice() !=null && request.getMaxPrice() != null){
                lambdaQueryWrapper.between(StoreProduct::getPrice,UnitConvertUtil.getInitialPrice(new BigDecimal(request.getMinPrice()),platRatio,merRatio)
                        ,UnitConvertUtil.getInitialPrice(new BigDecimal(request.getMaxPrice()),platRatio,merRatio));
            }
        }
        //价格排序
        if (request.getPriceSort() != null){
            if (request.getPriceSort() == 0){
                lambdaQueryWrapper.orderByAsc(StoreProduct::getPrice);
            }
            if (request.getPriceSort() == 1){
                lambdaQueryWrapper.orderByDesc(StoreProduct::getPrice);
            }
        }
        //折扣价查询条件
        RatioVo ratioVo = priceUtil.getRatio(channelMerchant);
        BigDecimal multiply = (ratioVo.getPlatRatio().movePointLeft(2).add(BigDecimal.ONE));
        StringBuilder ratio = new StringBuilder();
        ratio.append(" (CASE when is_europe = 1 then 1 ELSE ").append(multiply).append(" end) ");
        StringBuilder str = new StringBuilder();
        if(request.getMinDiscount() != null || request.getMaxDiscount() != null || request.getCostSort() != null){
            //头程
            str.append(" (CASE when is_europe = 1 then 0 ELSE ");
            str.append(" (CASE when is_europe = 29 then 20 when is_europe = 31 and temp_id =1 then 20 when temp_id <> 1 and left(suppliers_name,2)=\"HK\" then 30");
            str.append(" ELSE  0 end) end)");
        }
        BigDecimal agentRatio = BigDecimal.ONE;
        if (ratioVo.getFirstAgentRatio() != null) {
            agentRatio = agentRatio.multiply(ratioVo.getFirstAgentRatio().movePointLeft(2).add(BigDecimal.ONE));
        }
        if (ratioVo.getSecondAgentRatio() != null) {
            agentRatio = agentRatio.multiply(ratioVo.getSecondAgentRatio().movePointLeft(2).add(BigDecimal.ONE));
        }
        if (request.getMinDiscount() != null && request.getMaxDiscount() == null){
            lambdaQueryWrapper.apply("CEILING( (cost * "+ ratio +" + "+ str +" ) * "+ agentRatio +" / (ot_price * exchange_rate)*100) / 10 >= {0} ",request.getMinDiscount());
        }else if(request.getMinDiscount() == null && request.getMaxDiscount() != null){
            lambdaQueryWrapper.apply("CEILING( (cost * "+ ratio +" + "+ str +" ) * "+ agentRatio +" / (ot_price * exchange_rate)*100) / 10 <= {0} ",request.getMaxDiscount());
        }else if(request.getMinDiscount() != null && request.getMaxDiscount() != null){
            lambdaQueryWrapper.apply("CEILING( (cost * "+ ratio +" + "+ str +" ) * "+ agentRatio +" / (ot_price * exchange_rate)*100) / 10 BETWEEN  {0} and {1} ",request.getMinDiscount(), request.getMaxDiscount());
        }

        // 成本价折扣排序
        if (request.getCostSort() != null) {
            String value = request.getCostSort() == 0 ? "ASC" : "DESC";
            lambdaQueryWrapper.last(" ORDER BY CEILING( (cost * "+ ratio +" + "+ str +" ) * "+ agentRatio +" / (ot_price * exchange_rate)*100) / 10 " + value );
        // 库存排序
        } else if(7 == request.getType()) {
            lambdaQueryWrapper.orderByDesc(StoreProduct :: getStock);
        // 昨日热销
        } else if(8 == request.getType()){
            return lambdaQueryWrapper;
        // 近30天热销
        } else if(9 == request.getType()){
            return lambdaQueryWrapper;
        } else {
            lambdaQueryWrapper.orderByDesc(StoreProduct :: getLastPushTime);
        }

        return lambdaQueryWrapper;
    }

}
